<script setup>
	import { ref } from 'vue'
	import { LoginByPasswordApi } from '@/apis/user'
	import { useUserStore } from '@/stores/user'
	//用户的相关信息
	const userStore = useUserStore()
	//获取表单元素
	const formData = ref({
		mobile: '',
		password: '',
	})
	//表单校验
	const form = ref()

	// 验证表单数据的规则
	const formRules = {
		mobile: {
			rules: [
				{ required: true, errorMessage: '请填写手机号码' },
				{ pattern: '^1\\d{10}$', errorMessage: '手机号码格式不正确' },
			],
		},
		password: {
			rules: [
				{ required: true, errorMessage: '请填入正确的密码' },
				{ pattern: /^abc\d{5}$/, errorMessage: '输入的密码不正确' },
			],
		},
	}

	//判断是否同意用户协议

	const isAgree = ref(false)
	//点击登录实现账号密码登录
	const LoginByPassword = async () => {
		if (!isAgree.value) {
			return uni.showToast({
				title: '请勾选用户协议',
				icon: 'error',
			})
		}
		try {
			//校验表单元素
			await form.value.validate()
			//调用登录接口  实现登录
			const res = await LoginByPasswordApi({
				mobile: formData.value.mobile,
				password: formData.value.password,
			})
			console.log(res)

			//持久化Token
			userStore.token = res.token

			//提示用户
			uni.showToast({
				title: '登录成功',
				icon: 'success',
			})
			//跳转页面
			uni.switchTab({
				url: '/pages/my/index',
			})
		} catch (e) {
			//TODO handle the exception
			console.log(e)
		}
	}
	const radioChange = () => {
		isAgree.value = !isAgree.value
	}
</script>
<template>
	<uni-forms class="login-form" ref="form" :model="formData" :rules="formRules">
		<uni-forms-item name="mobile">
			<uni-easyinput
				v-model="formData.mobile"
				:input-border="false"
				:clearable="false"
				placeholder="请输入手机号"
				placeholder-style="color: #C3C3C5"
			/>
		</uni-forms-item>
		<uni-forms-item name="password">
			<uni-easyinput
				v-model="formData.password"
				type="password"
				placeholder="请输入密码"
				:input-border="false"
				placeholder-style="color: #C3C3C5"
			/>
		</uni-forms-item>
		<view class="agreement">
			<radio :checked="isAgree" @tap="radioChange" color="#16C2A3" />
			我已同意
			<text class="link">用户协议</text>
			及
			<text class="link">隐私协议</text>
		</view>

		<button @tap="LoginByPassword" class="uni-button">登 录</button>
		<navigator hover-class="none" class="uni-navigator" url=" "> 忘记密码？ </navigator>
	</uni-forms>
</template>

<script>
	export default {
		options: {
			styleIsolation: 'shared',
		},
	}
</script>

<style lang="scss">
	@import './styles.scss';
</style>
